package com.sinodata.bsm.center.web.action.resource;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sino.uam.entity.Department;
import com.sino.uam.entity.UserInfo;
import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.bean.RelationHelper;
import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.cache.DataTypeCache;
import com.sinodata.bsm.center.cache.DimensionCache;
import com.sinodata.bsm.center.cache.DimensionTypeCache;
import com.sinodata.bsm.center.cache.EventTypeCache;
import com.sinodata.bsm.center.cache.RelationTypeCache;
import com.sinodata.bsm.center.cache.ResFindDefCache;
import com.sinodata.bsm.center.cache.ResTypeCache;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.event.EventTypeService;
import com.sinodata.bsm.center.service.probe.ProbeService;
import com.sinodata.bsm.center.service.relation.ResRelationService;
import com.sinodata.bsm.center.service.resource.AttributeService;
import com.sinodata.bsm.center.service.resource.CollectTaskService;
import com.sinodata.bsm.center.service.resource.ResGroupService;
import com.sinodata.bsm.center.service.resource.ResService;
import com.sinodata.bsm.center.service.resource.ResTypeService;
import com.sinodata.bsm.center.service.resource.ResViewService;
import com.sinodata.bsm.center.user.UserUtil;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.ResConstants;
import com.sinodata.bsm.common.constants.ResGroupTypeMap;
import com.sinodata.bsm.common.exception.AppException;
import com.sinodata.bsm.common.vo.Attribute;
import com.sinodata.bsm.common.vo.CollectField;
import com.sinodata.bsm.common.vo.CollectParam;
import com.sinodata.bsm.common.vo.CollectSchedule;
import com.sinodata.bsm.common.vo.CollectTask;
import com.sinodata.bsm.common.vo.DataType;
import com.sinodata.bsm.common.vo.Dimension;
import com.sinodata.bsm.common.vo.DimensionType;
import com.sinodata.bsm.common.vo.EventType;
import com.sinodata.bsm.common.vo.MotiResRel;
import com.sinodata.bsm.common.vo.Probe;
import com.sinodata.bsm.common.vo.PropertyDisplay;
import com.sinodata.bsm.common.vo.RelationType;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.common.vo.ResAttrVal;
import com.sinodata.bsm.common.vo.ResGroup;
import com.sinodata.bsm.common.vo.ResRelation;
import com.sinodata.bsm.common.vo.ResType;
import com.sinodata.bsm.common.vo.ResView;

/**
 * <p>
 * Description:
 * </p>
 * 
 * @author liulibo
 * @version 1.0
 * 
 * <p>
 * History:
 * 
 * Date Author Version Description
 * ---------------------------------------------------------------------------------
 * 2012-5-7 下午4:07:21 liulibo 1.0 To create
 * </p>
 * 
 * @since
 * @see
 */
public class ResAction extends BaseAction<Res> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Res entity;
    private Long id;
    private Long[] ids;
    @Autowired
    private ResService resService;
    @Autowired
    private CollectTaskService collectTaskService;
    @Autowired
    private ProbeService probeService;
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private ResRelationService resRelationService;
    @Autowired
    private ResTypeService resTypeService;
    @Autowired
    private DataTypeCache dataTypeCache;
    @Autowired
    private EventTypeService eventTypeService;
    @Autowired
    private EventTypeCache eventTypeCache;
    @Autowired
    private DimensionTypeCache dimensionTypeCache;
    @Autowired
    private DimensionCache dimensionCache;

    @Autowired
    private ResGroupService resGroupService;
    @Autowired
    protected ResTypeCache resTypeCache;

    private Page<Res> page;

    @Override
    public String delete() throws Exception {
        logger.info(">>>>>> enter delete action,id=" + this.id);
        try {
            String parentId = request.getParameter("pId");
            String viewId = request.getParameter("viewId");
            if (viewId != null) {
                resService.deleteTopResource(Long.parseLong(viewId), this.id);
                request.getSession().removeAttribute("nodeTrace");
            } else {
                resService.deleteResource(Long.parseLong(parentId), this.id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 删除没有子资源的资源
    public String deleteByIsChildRes() throws Exception {
        if (ids != null && ids.length > 0) {
            resService.deleteByIsChildRes(ids);
        }
        return null;
    }

    /**
     * 
     * @return
     * @throws Exception
     */
    public String deleteByResType() throws Exception {
        String resTypeId = request.getParameter("resTypeId");
        ResBean[] children = ResBean.get(this.id).childrenByType(Long.parseLong(resTypeId));
        for (ResBean child : children) {
            resService.deleteResource(this.id, child.res().getId());
        }
        return null;
    }

    /**
     * 子资源 分组列表显示
     * @return
     */
    public String childen() {
        Long parentResId = id;
        List<ResBean> children = RelationHelper.children(parentResId);
        List<List<ResBean>> types = new ArrayList<List<ResBean>>();
        for (ResBean child : children) {
            List<ResBean> type = null;
            for (int j = 0; j < types.size(); j++) {
                if (types.get(j).get(0).res().getResTypeId().longValue() == child.res().getResTypeId().longValue()) {
                    type = types.get(j);
                    break;
                }
            }
            if (type == null) {
                type = new ArrayList<ResBean>();
                types.add(type);
            }
            type.add(child);
        }
        //排序 按子资源多到少
        int loopNumber = types.size();
        for (int i = 0; i < loopNumber - 1; i++) {
            for (int c = 0; c < loopNumber - 1 - i; c++) {
                List<ResBean> prevBean = types.get(c);
                List<ResBean> compareBean = types.get(c + 1);
                if (prevBean.size() < compareBean.size()) {
                    types.set(c, compareBean);
                    types.set(c + 1, prevBean);
                }
            }
        }
        JSONArray attributes = new JSONArray();
        for (List<ResBean> resBeans : types) {
            Res res = resBeans.get(0).res();
            ResType resType = ResTypeBean.get(res.getResTypeId()).resType();
            for (int i = 0; i < resBeans.size(); i++) {
                attributes.add(resBeans.get(i).res());
            }
        }
        Struts2Utils.setRequestAttribute("attributes", attributes);
        System.out.println(attributes.toString());
        return "childen";
    }

    /**
     * 资源增加向导页
     * 
     * @return
     */
    public String guide() {
        Struts2Utils.setRequestAttribute("ntype", request.getParameter("ntype"));
        Struts2Utils.setRequestAttribute("id", request.getParameter("id"));
        Struts2Utils.setRequestAttribute("viewId", request.getParameter("viewId"));
        return "guide";
    }

    @SuppressWarnings("unchecked")
    @Override
    public String input() throws Exception {
        String ntype = request.getParameter("ntype");
        String id = request.getParameter("id");
        Long resId = null;
        if (ntype.equals("5")) {
            // resgroup
            ResGroup group = resGroupService.get(Long.parseLong(id));
            if (group.getResId() != null) {
                resId = group.getResId();
            }
        } else if (ntype.equals("4")) {
            // monitype
        } else if (ntype.equals("2")) {
            // 说明是资源
            resId = Long.parseLong(id);
        }

        if (resId != null) {
            entity = resService.get(resId);
        }
        String viewId = request.getParameter("viewId");
        if (viewId != null && !viewId.equals("null") && !viewId.equals("")) {
            ResView view = SpringContextHolder.getBean(ResViewService.class).get(Long.parseLong(viewId));
            request.setAttribute("resView", view);
        }

        request.setAttribute("res", entity);
        List<Probe> probeList = probeService.findAllProbe();
        Collections.sort(probeList, new ProbeSort());
        request.setAttribute("probeList", probeList);

        Boolean isResFind = false;
        if (request.getParameter("resTypeId") != null) {
            ResType type = ResTypeBean.get(Long.parseLong(request.getParameter("resTypeId"))).resType();
            type.setName(type.getName().trim());
            ResFindDefCache resFindDefCache = SpringContextHolder.getBean(ResFindDefCache.class);
            isResFind = resFindDefCache.getForResType(type.getId()) == null ? false : true; // 有无发现程序
            request.setAttribute("resType", type);
        }

        // 添加资源维度功能代码
        List<DimensionType> dimensionTypeList = dimensionTypeCache.getAll();
        Map<String, List<Dimension>> dimensionMap = new HashMap<String, List<Dimension>>();
        for (DimensionType dimensionType : dimensionTypeList) {
            List<Dimension> dimensionList = dimensionCache.getDimensionByType(dimensionType.getId());
            dimensionMap.put("key" + dimensionType.getId(), dimensionList);
        }

        request.setAttribute("ntype", ntype);
        request.setAttribute("typeId", id);
        request.setAttribute("isResFindDef", isResFind);
        request.setAttribute("agreement", request.getParameter("agreement"));

        // 存储维度数据
        JSONObject dimensionJson = JSONObject.fromObject(dimensionMap);
        request.setAttribute("dimensionTypeList", dimensionTypeList);
        request.setAttribute("dimensionMap", dimensionJson);
        return "input";
    }

    public String propertyEventtypeInput() {
        System.out.println("aaaa");
        String id = request.getParameter("id");
        if (id != null && !id.equals("")) {
            entity = resService.get(Long.parseLong(id));
        }
        String viewId = request.getParameter("viewId");
        if (viewId != null && !viewId.equals("null") && !viewId.equals("")) {
            ResView view = SpringContextHolder.getBean(ResViewService.class).get(Long.parseLong(viewId));
            request.setAttribute("resView", view);
        }

        request.setAttribute("res", entity);
        List<Probe> probeList = probeService.findAllCicpProbe();
        Collections.sort(probeList, new ProbeSort());
        request.setAttribute("probeList", probeList);

        Boolean isResFind = false;
        if (request.getParameter("resTypeId") != null) {
            ResType type = ResTypeBean.get(Long.parseLong(request.getParameter("resTypeId"))).resType();
            type.setName(type.getName().trim());
            ResFindDefCache resFindDefCache = SpringContextHolder.getBean(ResFindDefCache.class);
            isResFind = resFindDefCache.getForResType(type.getId()) == null ? false : true; // 有无发现程序
            request.setAttribute("resType", type);
        }
        request.setAttribute("isResFindDef", isResFind);
        request.setAttribute("agreement", request.getParameter("agreement"));
        return "inputpropertyeventtype";
    }

    public String inputEventtype() throws Exception {
        return "inputeventtype";
    }

    public String inputProperty() throws Exception {
        List<DataType> dataTypes = dataTypeCache.getAll();
        Struts2Utils.setRequestAttribute("dataTypes", dataTypes);
        return "inputproperty";
    }

    public String addframe() throws Exception {
        String resId = request.getParameter("id");
        String viewId = request.getParameter("viewId");

        if (resId != null) {
            request.setAttribute("hasExitPrivalige", UserFunctionValidate.resFunctionValidate(Long.parseLong(resId), FunctionConstants.EDIT_RES));
        }
        request.setAttribute("viewHasAddResPrivalige", UserFunctionValidate.viewFunctionValidate(Long.parseLong(viewId), FunctionConstants.VIEW_ADD_RES));
        request.setAttribute("id", resId);
        request.setAttribute("viewId", viewId);
        return "addframe";
    }

    public String view() throws Exception {
        entity = resService.get(id);
        String pId = request.getParameter("pId");
        ResRelation resRelation = null;
        if (pId != null && !pId.equals("0") && !pId.equals("")) {
            List<ResRelation> relList = resRelationService.getResRelationsOfRes(id);
            for (ResRelation rel : relList) {
                if (rel.getStartId().longValue() == Long.parseLong(pId) && rel.getEndId().longValue() == id.longValue()) {
                    resRelation = rel;
                    break;
                }
            }
        }
        // RelationTypeCache
        if (resRelation != null) {
            RelationType reltype = SpringContextHolder.getBean(RelationTypeCache.class).get(resRelation.getRelationTypeId());
            request.setAttribute("parentRes", resService.get(resRelation.getStartId()));
            request.setAttribute("relationType", reltype);
        }

        ResTypeBean typeBean = ResTypeBean.get(entity.getResTypeId());
        ResType resType = typeBean.resType();
        request.setAttribute("resType", resType);
        request.setAttribute("res", entity);
        Probe p = probeService.findById(entity.getProbeId());
        request.setAttribute("probe", p);

        List<Attribute> attributes = new ArrayList<Attribute>();
        // if (typeBean.resType().getFoundFlag() == 0) {
        attributes.addAll(typeBean.attributes());
        // }

        Map<Long, String> map = new HashMap<Long, String>();
        for (Attribute att : attributes) {
            ResAttrVal val = attributeService.getResAttrVal(id, att.getId().longValue());
            map.put(att.getId().longValue(), val == null ? "" : val.getAttrValue());

        }
        request.setAttribute("attributes", attributes);
        request.setAttribute("attVals", map);

        return "view";
    }

    @Override
    public String list() throws Exception {
        // 子资源
        ResBean[] resBeans = ResBean.get(id).children();
        JSONArray childRes = new JSONArray();
        JSONObject json = new JSONObject();
        for (ResBean resBean : resBeans) {
            Res res = resBean.res();
            JSONObject object = new JSONObject();
            object.element("operate", "");
            object.element("id", res.getId());
            object.element("name", res.getName());
            object.element("ip", res.getIp());
            object.element("resTypeId", res.getResTypeId());
            ResTypeBean bean = ResTypeBean.get(res.getResTypeId());
            ResType type = bean.resType();
            object.element("resTypeName", type.getName());
            object.element("desc", res.getDesc() == null ? "" : res.getDesc());
            Probe probe = probeService.findById(res.getProbeId());
            object.element("probeId", res.getProbeId());
            object.element("probeName", probe == null ? "" : probe.getName());
            childRes.add(object);
        }

        json.element("aaData", childRes);
        json.element("iTotalRecords", 0);
        json.element("iTotalDisplayRecords", 0);
        Struts2Utils.renderText(json.toString());
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {

        if (id == null) {
            entity = new Res();
        } else {
            entity = resService.get(id);
        }

    }

    @SuppressWarnings("rawtypes")
    @Override
    public String save() throws Exception {
        String flag = request.getParameter("flag");
        String parentId = request.getParameter("parentId");
        String isRoot = request.getParameter("isRoot");
        String str_view = request.getParameter("viewId");
        if (isRoot != null) {
            parentId = null;
        }
        String ntype = request.getParameter("ntype");
        String typeId = request.getParameter("typeId");
        Long groupId = null;
        if (ntype != null && ntype.equals("5")) {
            // 资源组
            ResGroup group = resGroupService.get(Long.parseLong(typeId));
            if (group.getType() == 4) {
                // 说明是资源组下,monitype有值，并且添加的资源必须属于monitype
                Long mt = resTypeCache.getMoitTypeId(entity.getResTypeId());
                if (mt != null && mt.longValue() == group.getMonitorTypeId()) {
                    // 才可以挂在此目录下
                    groupId = group.getId();
                }
            } else if (group.getType() == 2) {
                // 说明是资源下的资源组。
                Long containType = group.getContainType();
                if (containType != null) {
                    // 则有限制
                    Long[] resTypes = ResGroupTypeMap.getResType(containType.longValue());
                    long resTypeId = entity.getResTypeId();
                    for (Long t : resTypes) {
                        ResTypeBean typebean = ResTypeBean.get(resTypeId);
                        do {
                            if (t.longValue() == typebean.resType().getId()) {
                                groupId = group.getId();
                                break;
                            }
                        } while ((typebean = typebean.parent()) != null);
                    }
                } else {
                    // 则直接挂在该资源组下，并和父资源建立关系
                    groupId = group.getId();
                }
            }
        } else if (ntype != null && ntype.equals("4")) {
            // monitype,直接持在monitype下的
            parentId = null;
            str_view = null;
        }
        if (flag == null || flag.equals("")) {
            Enumeration en = request.getParameterNames();
            entity.setHealthStatus(ResConstants.NORMAL_USABLE);
            entity.setPaused(ResConstants.RES_NOT_PAUSED);

            List<ResAttrVal> attValList = new ArrayList<ResAttrVal>();
            while (en.hasMoreElements()) {
                String attname = (String) en.nextElement();
                String val = request.getParameter(attname);
                if (attname.indexOf("prop_") == -1)
                    continue;
                if (val != null && !"".equals(val)) {
                    ResAttrVal attval = new ResAttrVal();
                    long attrId = Long.parseLong(attname.substring(5));
                    attval.setAttrId(attrId);
                    attval.setAttrValue(val);
                    attValList.add(attval);
                }
            }
            ResGroup group = null;
            if (groupId != null) {
                group = resGroupService.get(groupId);
                if (group.getResId() != null) {
                    parentId = group.getResId().toString();
                }
            }
            if (parentId != null && !parentId.equals("")) {
                String resRelId = request.getParameter("resRelId");
                resService.addResource(Long.parseLong(parentId), entity, attValList, Long.parseLong(resRelId));
            } else {
                Long viewId = null;
                if (str_view != null && !str_view.equals("")) {
                    viewId = Long.parseLong(str_view);
                }
                resService.addTopResource(viewId, entity, attValList);
            }
            if (group != null) {
                MotiResRel _motiResRel = new MotiResRel();
                _motiResRel.setResGroupId(group.getId());
                _motiResRel.setResId(entity.getId());
                try {
                    resGroupService.saveMotiResRel(_motiResRel);
                } catch (AppException ex) {
                    logger.error("", ex);
                }
            }

            JSONObject object = new JSONObject();
            object.element("isFind", "false");
            object.element("resId", entity.getId());
            ResType resType = resTypeService.get(entity.getResTypeId());
            if (resType.getFoundFlag() == null || resType.getFoundFlag() == 0) {
                object.element("isFind", "false");
            } else {
                object.element("isFind", "true");
            }
            // 添加维度信息

            Struts2Utils.renderText(object.toString());
        } else {
            String propertyData = request.getParameter("propertyData");
            String eventTypeData = request.getParameter("eventTypeData");

            entity.setHealthStatus(ResConstants.NORMAL_USABLE);
            entity.setPaused(ResConstants.RES_NOT_PAUSED);

            if (parentId != null && !parentId.equals("")) {
                String resRelId = request.getParameter("resRelId");
                resService.addResource(Long.parseLong(parentId), entity, new ArrayList<ResAttrVal>(), Long.parseLong(resRelId));
            } else {
                String viewId = request.getParameter("viewId");
                resService.addTopResource(Long.parseLong(viewId), entity, new ArrayList<ResAttrVal>());
            }

            List<CollectParam> collectParamList = new ArrayList<CollectParam>();
            List<CollectField> collectFieldList = new ArrayList<CollectField>();

            // 添加采集任务
            String resTypeId = String.valueOf(entity.getResTypeId());
            CollectTask collectTask = new CollectTask();
            collectTask.setResId(entity.getId());
            collectTask.setCollectorId(resTypeId.equals("1205040600000") ? 10l : 15l);
            collectTask.setStatus(1);
            collectTask.setIsSave(1);

            // 添加采集参数--需要和采集程序对应start
            String dBType = request.getParameter("DBType");
            String dBName = request.getParameter("DBName");
            String sQL = request.getParameter("SQL");
            String regex = request.getParameter("regex");
            String shell = request.getParameter("shell");
            Map<String, String> map = new HashMap<String, String>();
            if (resTypeId.equals("1205040600000")) {
                map.put("Regex", regex);
                map.put("collectCmd", shell);
            } else if (resTypeId.equals("1205040500000")) {
                map.put("DBType", dBType);
                map.put("DBName", dBName);
                map.put("SQL", sQL);
            }
            for (String param : map.keySet()) {
                CollectParam collectParam = new CollectParam();
                collectParam.setParamValue(map.get(param));
                collectParam.setParamName(param);
                collectParamList.add(collectParam);
            }
            CollectParam collectParam = new CollectParam();
            collectParam.setParamValue(propertyData != null ? String.valueOf(propertyData.split(",").length) : "0");
            collectParam.setParamName("FieldNum");
            collectParamList.add(collectParam);
            // end
            // 添加采集字段
            int collectFieldNum = 1;
            if (propertyData != null && !propertyData.equals("")) {
                String[] propertyArray = propertyData.split(",");
                for (int i = 0; i < propertyArray.length; i++) {
                    String name = propertyArray[i].split("[|]")[0];
                    Integer dateTypeId = Integer.parseInt(propertyArray[i].split("[|]")[1]);
                    Long propertyId = resService.getMyPropertyIdByDateTypeIdResTypeId(dateTypeId, entity.getResTypeId(), entity.getId());
                    CollectField collectField = new CollectField();
                    collectField.setProp(propertyId);
                    collectField.setFieldName("$" + collectFieldNum++);
                    collectFieldList.add(collectField);
                    PropertyDisplay propertyDisplay = new PropertyDisplay();
                    propertyDisplay.setDisplayName(name);
                    propertyDisplay.setResId(entity.getId());
                    propertyDisplay.setResType(entity.getResTypeId());
                    propertyDisplay.setPropId(propertyId);
                    // 添加资源指标名称对应关系
                    collectTaskService.addPropertyDisplay(propertyDisplay);
                }
            }
            // 添加事件类别
            if (eventTypeData != null && !eventTypeData.equals("")) {
                String[] eventTypeArray = eventTypeData.split(",");
                for (int i = 0; i < eventTypeArray.length; i++) {
                    EventType eventType = new EventType();
                    eventType.setName(eventTypeArray[i].split("[|]")[0]);
                    eventType.setRecoverable(Integer.valueOf(eventTypeArray[i].split("[|]")[1]));
                    eventType.setResId(entity.getId());
                    eventTypeService.add(eventType);
                    eventTypeCache.put(eventType.getId(), eventType);
                }
            }

            collectTaskService.saveOrUpdateCollectTask(collectTask, new ArrayList<CollectSchedule>(), collectParamList, collectFieldList);

            JSONObject object = new JSONObject();
            object.element("isFind", "false");
            object.element("resId", entity.getId());
            ResType resType = resTypeService.get(entity.getResTypeId());
            if (resType.getFoundFlag() == null || resType.getFoundFlag() == 0) {
                object.element("isFind", "false");
            } else {
                object.element("isFind", "true");
            }
            Struts2Utils.renderText(object.toString());
        }
        afterSaveRes();
        return null;
    }

    public String add() throws Exception {
        return null;
    }

    public String initUpdate() {
        entity = resService.get(id);
        String pId = Struts2Utils.getParameter("pId");
        String viewId = Struts2Utils.getParameter("viewId");
        ResRelation resRelation = null;
        if (pId != null && !pId.equals("")) {
            List<ResRelation> relList = resRelationService.getResRelationsOfRes(id);
            for (ResRelation rel : relList) {
                if (rel.getStartId().longValue() == Long.parseLong(pId) && rel.getEndId().longValue() == id.longValue()) {
                    resRelation = rel;
                    break;

                }
            }
        }

        // RelationTypeCache
        if (resRelation != null) {
            RelationType reltype = SpringContextHolder.getBean(RelationTypeCache.class).get(resRelation.getRelationTypeId());
            request.setAttribute("parentRes", resService.get(resRelation.getStartId()));
            request.setAttribute("relationType", reltype);
        }

        ResTypeBean typeBean = ResTypeBean.get(entity.getResTypeId());
        ResType resType = typeBean.resType();
        request.setAttribute("resType", resType);
        request.setAttribute("res", entity);
        Probe p = probeService.findById(entity.getProbeId());
        request.setAttribute("probe", p);

        List<Attribute> attributes = new ArrayList<Attribute>();
        attributes.addAll(typeBean.attributes());

        // 用户自定义属性
        List<Attribute> definedAttribute = attributeService.findAttributeByResId(id);
        if (definedAttribute != null) {
            attributes.addAll(definedAttribute);
        }

        Map<Long, String> map = new HashMap<Long, String>();
        for (Attribute att : attributes) {
            ResAttrVal val = attributeService.getResAttrVal(id, att.getId().longValue());
            map.put(att.getId().longValue(), val == null ? "" : val.getAttrValue());
        }

        List<DimensionType> dimensionTypeList = dimensionTypeCache.getAll();
        Map<String, List<Dimension>> dimensionMap = new HashMap<String, List<Dimension>>();
        for (DimensionType dimensionType : dimensionTypeList) {
            List<Dimension> dimensionList = dimensionCache.getDimensionByType(dimensionType.getId());
            dimensionMap.put("key" + dimensionType.getId(), dimensionList);
        }

        request.setAttribute("attributes", attributes);
        request.setAttribute("attVals", map);
        request.setAttribute("viewId", viewId);

        JSONObject dimensionJson = JSONObject.fromObject(dimensionMap);
        request.setAttribute("dimensionTypeList", dimensionTypeList);
        request.setAttribute("dimensionMap", dimensionJson);
        return "update";
    }

    @SuppressWarnings("rawtypes")
    public String update() throws Exception {
        entity = resService.get(id);
        String[] administrators = request.getParameterValues("administrator");
        String administrator = null;
        if (administrators != null && administrators.length > 0) {
            administrator = administrators[0].trim();
            for (int i = 1; i < administrators.length; i++) {
                administrator += "," + administrators[i].trim();
            }
        }
        entity.setAdministrator(administrator);
        String resname = request.getParameter("name");
        entity.setName(resname);
        String code = request.getParameter("code");
        entity.setCode(code);
        String desc = request.getParameter("desc");
        entity.setDesc(desc);

        String ip = request.getParameter("ip");
        entity.setIp(ip);
        String interId = request.getParameter("internalId");
        entity.setInternalId(interId);

        List<ResAttrVal> attValList = new ArrayList<ResAttrVal>();
        Enumeration en = request.getParameterNames();
        String pId = request.getParameter("pId");
        ResRelation resRelation = null;
        String resRelId = request.getParameter("resRelId");
        if (pId != null && !pId.equals("")) {
            resRelation = new ResRelation();
            resRelation.setStartId(Long.parseLong(pId));
            resRelation.setEndId(entity.getId());
            resRelation.setRelationTypeId(Long.parseLong(resRelId));
        }

        while (en.hasMoreElements()) {
            String attname = (String) en.nextElement();
            if (attname.indexOf("prop_") == -1)
                continue;
            String val = request.getParameter(attname);
            long attrId = Long.parseLong(attname.substring(5));
            ResAttrVal attval = attributeService.getResAttrVal(entity.getId(), attrId);
            if (val == null || val.equals("")) {
                if (attval != null) {
                    attributeService.deleteResAttrVal(attval);
                }
            }
            if (attval == null) {
                attval = new ResAttrVal();
                attval.setAttrId(attrId);
            }

            attval.setAttrValue(val);
            attValList.add(attval);
        }

        resService.updateResource(entity, attValList, resRelation);
        return null;
    }

    /**
     * 跳转到我的视图-资源信息页面
     * 
     * @return
     * @throws Exception
     */
    public String baseinfo() throws Exception {

        return "baseinfo";
    }

    /**
     * 跳转到事件管理-资源查询页面
     * 
     * @return
     */
    public String search() {
        List<Probe> probes = probeService.findAllProbe();

        Struts2Utils.setRequestAttribute("probes", probes);
        return "search";
    }

    /**
     * 资源查询结果
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public String query() {
        try {
            Page p = new Page();
            String dimension = request.getParameter("dimension");
            Enumeration<String> names = Struts2Utils.getRequest().getParameterNames();
            Map<String, String> parameterMap = new HashMap<String, String>();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                if (name.indexOf("FILTER") != -1) {
                    String value = Struts2Utils.getRequest().getParameter(name);
                    parameterMap.put(name.substring(name.indexOf("_") + 1), value);
                }
            }

            // 当前用户可访问的资源
            List<Long> authScopeList = UserFunctionValidate.getResIdListForUser(FunctionConstants.VIEW_RES);
            StringBuffer authorizeRes = new StringBuffer(authScopeList == null || authScopeList.size() <= 0 ? "-999" : "");
            for (int i = 0; authScopeList != null && i < authScopeList.size(); i++) {
                Long resId = authScopeList.get(i);
                authorizeRes.append(resId);
                if (i != (authScopeList.size() - 1)) {
                    authorizeRes.append(",");
                }
            }
            parameterMap.put("resIds", authorizeRes.toString());

            Condition condition = new Condition();
            condition.setWhere(parameterMap);

            int pageSize = Integer.parseInt(request.getParameter("iDisplayLength"));
            int start = Integer.parseInt(request.getParameter("iDisplayStart"));
            int pageno = (start / pageSize) + 1;
            p.setPageNo(pageno);
            p.setPageSize(pageSize);

            List<Res> list = resService.search(p, condition, dimension);
            String[] str = ResConstants.HEALTH_DESC;
            JSONArray array = new JSONArray();
            for (int t = 0; list != null && t < list.size(); t++) {
                Res r = list.get(t);
                JSONObject entity = new JSONObject();
                entity.element("checkbox", "<input type='checkbox' name='resCheck' value='" + r.getId() + "' />");
                entity.element("id", r.getId());
                entity.element("resTypeId", r.getResTypeId());

                List<ResBean> parentList = RelationHelper.parents(r.getId());
                // 寻找父资源
                ResBean parent = parentList.size() > 0 ? parentList.get(0) : null;

                StringBuffer parentNameValue = new StringBuffer("");
                List<ResBean> parentBeans = new ArrayList<ResBean>();
                while (parent != null) {
                    List<ResBean> tempParent = RelationHelper.parents(parent.res().getId());
                    if (parent != null) {
                        parentBeans.add(parent);
                    }
                    if (tempParent.size() > 0) {
                        parent = tempParent.get(0);

                    } else {
                        parent = null;
                    }
                }

                for (int i = parentBeans.size() - 1; i >= 0; i--) {
                    Res ob = parentBeans.get(i).res();
                    parentNameValue.append(ob.getName() + "/");
                }
                entity.element("resName", parentNameValue.toString() + r.getName());

                Probe probe = probeService.findById(r.getProbeId());
                entity.element("probeName", probe != null ? probe.getName() : "");
                entity.element("ip", r.getIp());

                ResTypeBean typeBean = ResTypeBean.get(r.getResTypeId());
                ResType type = typeBean.resType();
                entity.element("resTypeName", type.getName());
                entity.element("statu", r.getPaused().intValue() == 0 ? "正常监控" : "已暂停");
                entity.element("healthStatus", r.getHealthStatus().intValue());
                entity.element("healthStatusStr", str[r.getHealthStatus().intValue() - 1]);
                entity.element("desc", r.getDesc() == null ? "" : r.getDesc());
                array.add(entity);
            }

            JSONObject json = new JSONObject();
            json.element("aaData", array);
            json.element("iTotalRecords", p.getTotal());
            json.element("iTotalDisplayRecords", p.getTotal());
            Struts2Utils.renderText(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 保存资源后需要做的事情
     */
    private void afterSaveRes() {
        if (entity.getResTypeId() == 1105050000000L) {
            // 如果是应用系统类型，则需要自动加上资源组
            resGroupService.saveApplicationGroup(entity.getId());
        }
    }

    /**
     * 资源名称匹配(资源查询 资源名称有用到)
     * 
     * @return
     */
    public String matching() {
        String keyValue = Struts2Utils.getParameter("resName");
        if (!keyValue.equals("")) {
            List<Res> list = resService.findAll();
            List<String> matchValues = new ArrayList<String>();
            Map<String, String> valueMap = new HashMap<String, String>();
            for (int i = 0; i < list.size(); i++) {
                String resName = list.get(i).getName();
                if (resName.contains(keyValue)) {
                    valueMap.put(resName, resName);
                }

                if (valueMap.size() >= 10) {
                    break;
                }
            }
            matchValues.addAll(valueMap.values());
            Struts2Utils.renderJson(matchValues);
        }
        return null;
    }

    /**
     * 资源是否删除
     * 
     * @return true:已删除 false:未删除
     */
    public String isDelete() {
        Struts2Utils.renderText(" " + (resService.get(id) == null) + " ");
        return null;
    }

    /**
     * 设置设备负责人时,获取所以用户，
     * @return
     */
    public String getAllUsers() {
        Collection<Department> departmentCollection = UserUtil.getInstance().getAllDepartment();
        if (departmentCollection == null || departmentCollection.size() < 1) {
            logger.error("********没有获取到部门数据********");
            return null;
        }

        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        List<String> userIdList = new ArrayList<String>();
        for (Department department : departmentCollection) {
            List<UserInfo> userList = UserUtil.getInstance().getUserByDeptId(department.getId());
            if (userList != null && userList.size() > 0) {
                for (UserInfo user : userList) {
                    if (userIdList.contains(user.getId())) {
                        continue;
                    } else {
                        userIdList.add(user.getId());
                    }
                    String value = user.getFullName() + "(" + department.getName() + ")";
                    String key = user.getId();
                    JSONObject obj = new JSONObject();
                    obj.element("userId", key);
                    obj.element("userName", value);
                    array.add(obj);
                }
            }
        }
        json.element("users", array);
        Struts2Utils.renderText(json.toString());
        return null;
    }

    @Override
    public Res getModel() {
        return entity;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long[] getIds() {
        return ids;
    }

    public void setIds(Long[] ids) {
        this.ids = ids;
    }

    @SuppressWarnings("rawtypes")
    class ProbeSort implements Comparator {
        @Override
        public int compare(Object obj1, Object obj2) {
            Probe res1 = (Probe) obj1;
            Probe res2 = (Probe) obj2;
            if (Math.abs(res1.getStatus() - 3) > Math.abs(res2.getStatus() - 3)) {
                return 1;
            } else {
                return 0;
            }
        }
    }

}
